import React from 'react'
import { Link as RouterLink, withRouter } from 'react-router-dom'
import Grid from '@material-ui/core/Grid'
import WelcomPaper from 'Main/welcomPaper'
import BlogList from './blogList'
import { withStyles } from '@material-ui/core'
import BlogFilter from './blogFilter'
import Pagination from '@material-ui/lab/Pagination';

import axios, { BLOG_API } from 'API'
import { Category } from '@material-ui/icons'

const styles = (theme) => ({
  welcomPaper: {
    marginBottom: theme.spacing(2),
  },
  pagination: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    marginTop: theme.spacing(4),
  },
});

class BlogHome extends React.Component {
  constructor(props) {
    super(props);
    // 获取query paramaters
    const queryParams = new URLSearchParams(this.props.location.search);
    this.state = {
      blogs: [],
      dates: null,
      categories: null,
      pageNum: null,
      queryCategory: queryParams.get("category") || "",    // 当前筛选的类别
      queryYear: queryParams.get("year") || "",      // 当前筛选的日期
      queryMonth: queryParams.get("month") || "",      // 当前筛选的日期
      page: 1,
    };
    this.handleFilter = this.handleFilter.bind(this);
    this.handlePageChange = this.handlePageChange.bind(this);
    this.setBlogList = this.setBlogList.bind(this);
  }

  /**
   * 获取博客列表，返回Promise
   * @param {*} page 获取博客列表的页数
   */
  fetchBlogList(page = this.state.page, category = this.state.queryCategory,
    year = this.state.queryYear, month = this.state.queryMonth) {
    let params = {};
    page && (params.page = page);
    category && (params.category = category);
    year && (params.year = year);
    month && (params.month = month);
    // 处理搜索关键词
    const Params = new URLSearchParams(this.props.location.search);
    const searchKeywords = Params.get("key") || "";    //搜索的关键词
    searchKeywords && (params.key = searchKeywords);
    return axios.request({
      url: BLOG_API.blogList.url,
      method: BLOG_API.blogList.method,
      params
    }).then(response => {
      this.setBlogList(response.data);
      this.setState({
        queryCategory: category, queryYear: year, queryMonth: month
      })
    })
  }

  componentDidMount() {
    // 获取博客列表
    this.fetchBlogList();

    // 获取博客时间
    axios.request({
      url: BLOG_API.blogDate.url,
      method: BLOG_API.blogDate.method,
    }).then(response => {
      this.setState({ dates: response.data })
    });

    //获取博客类别
    axios.request({
      url: BLOG_API.blogCategory.url,
      method: BLOG_API.blogCategory.method,
    }).then(response => {
      this.setState({ categories: response.data })
    });
  }

  componentDidUpdate(preProps) {
    // 当url中的搜索参数变化时
    if (preProps.location.search !== this.props.location.search) {
      this.fetchBlogList();
    }
  }

  /**
   * 分页处理函数
   */
  handlePageChange(event, page) {
    this.fetchBlogList(page);
  }

  /**
   * 处理博客列表变化
   * @param {*} data 后台返回response的data
   */
  setBlogList(data) {
    this.setState({
      blogs: data.blogs,
      pageNum: data.page_count,
      page: data.current_page,
    });
  }

  handleFilter(category, year, month) {
    this.fetchBlogList(undefined, category, year, month);
  }

  renderPagination() {
    const { classes } = this.props;
    if (!this.state.pageNum) {
      return null;
    }
    return (
      <Pagination
        classes={{ root: classes.pagination }}
        count={this.state.pageNum}
        color="primary"
        onChange={this.handlePageChange}
        showFirstButton
        page={this.state.page}
        showLastButton />
    );
  }

  render() {
    const { classes } = this.props;
    return (
      <Grid container>
        <Grid item xs={12} className={classes.welcomPaper}>
          <WelcomPaper
            title="博客"
            description="探索你喜欢的文章" />
        </Grid>
        <Grid item xs={false} sm={1} />
        <Grid item xs={12} sm={8}>
          <BlogList blogs={this.state.blogs} />
        </Grid>
        <Grid item xs={false} sm={3} >
          <BlogFilter
            onSubmit={this.handleFilter}
            dates={this.state.dates}
            categories={this.state.categories}
            queryCategory={this.state.queryCategory}
            queryYear={this.state.queryYear}
            queryMonth={this.state.queryMonth} />
        </Grid>
        <Grid item xs={12}>
          {this.renderPagination()}
        </Grid>
      </Grid>
    )
  }
}

export default withRouter(withStyles(styles, { withTheme: true })(BlogHome));